const {clipboard} = require('electron')
const clippingsList = document.getElementById('clipping-list')
const copyFromClipboardButton = document.getElementById('copy-from-clipboard')

const createClippingElement = (clippingsTeXt) => {
  const clippingsElement = document.createElement('article')
  clippingsElement.classList.add('clippings-list-item')
  clippingsElement.innerHTML = `
    <div class="clipping-text" disabled="true">

    </div>
    <div class="clipping-controls">
      <button class="copy-clipping">
        Copy to Clipboard
      </button>
      <button class="publish-clipping">
        Publish 
      </button>
      <button class="remove-clipping">
        Remove
      </button>
    <div>
  `

  clippingsElement.querySelector('.clipping-text').innerHTML = clippingsTeXt
  return clippingsElement
}

const addClippingToList = () => {
  // 从剪贴板读取文本内容
  const clippingText = clipboard.readText()
  const clippingElement = createClippingElement(clippingText)
  clippingsList.prepend(clippingElement)
}

copyFromClipboardButton.addEventListener('click', addClippingToList)

clippingsList.addEventListener('click', event => {
  const hasClass = classNmae => {
    event.target.classList.contains(classNmae)
  }
  const clippingsListItem = getButtonParent(event)
  if (hasClass('remove-clipping')) removeClipping(clippingsListItem)
  if (hasClass('copy-clipping')) writeToClipboard(getClippingText(clippingsListItem))
  if (hasClass('publish-clipping')) writeToClipboard(getClippingText(clippingsListItem))
})

// 删除一个剪贴项
const removeClipping = target => {
  target.remove()
}

// 跟剪切项有关的辅助函数
const getButtonParent = ({target}) => {
  return target.parentNode.parentNode
}
const getClippingText = (clippingsListItem) => {
  return clippingsListItem.querySelector('.clipping-text').innerText
}

// 将剪切项文本写入剪贴板
const writeToClipboard = clippingsTeXt => {
  clipboard.writeText(clippingsTeXt)
}